import {
	createRouter,
	createWebHashHistory,
	type RouteRecordRaw,
} from "vue-router"
import useRouterStore from "@store/useRouterStore"
import { routerEventEmitter } from "@store/useRouterStore"
import Home from "@pages/home.vue"

// 使用常量定义路由名称避免硬编码
const RouteNames = {
	HOME: "home",
	ADD_TRAVEL_RECORD: "AddTravelRecord",
	TRAVEL_RECORD_MANAGEMENT: "TravelRecordManagement",
	TRAVEL_PEOPLE_MANAGEMENT: "TravelPeopleManagement",
	SYSTEM_DATA_MANAGEMENT: "SystemDataManagement",
	LUMP_SUM_CAR_FARE_MANAGEMENT: "LumpSumCarFareManagement",
	TRAVEL_ADDRESS_MANAGEMENT: "TravelAddressManagement",
} as const

// 使用路由懒加载封装函数
const lazyLoad = (path: string) => () => import(`@pages/${path}/${path}.vue`)

const routes: Array<RouteRecordRaw> = [
	{
		path: "/",
		redirect: "/home",
	},
	{
		path: "/home",
		name: RouteNames.HOME,
		component: Home,
	},
	{
		path: "/AddTravelRecord",
		name: RouteNames.ADD_TRAVEL_RECORD,
		component: lazyLoad("AddTravelRecord"),
	},
	{
		path: "/TravelRecordManagement",
		name: RouteNames.TRAVEL_RECORD_MANAGEMENT,
		component: lazyLoad("TravelRecordManagement"),
	},
	{
		path: "/TravelPeopleManagement",
		name: RouteNames.TRAVEL_PEOPLE_MANAGEMENT,
		component: lazyLoad("TravelPeopleManagement"),
	},
	{
		path: "/SystemDataManagement",
		name: RouteNames.SYSTEM_DATA_MANAGEMENT,
		component: lazyLoad("SystemDataManagement"),
	},
	{
		path: "/LumpSumCarFareManagement",
		name: RouteNames.LUMP_SUM_CAR_FARE_MANAGEMENT,
		component: lazyLoad("LumpSumCarFareManagement"),
	},
	{
		path: "/TravelAddressManagement",
		name: RouteNames.TRAVEL_ADDRESS_MANAGEMENT,
		component: lazyLoad("TravelAddressManagement"),
	},
]

const router = createRouter({
	history: createWebHashHistory(),
	routes,
	// 启用严格模式的路由匹配
	strict: true,
})
// 新增类型定义
type PageParams = Record<string, unknown> | { [key: string]: unknown }

/**
 * 处理页面参数事件触发（类型安全版本）
 */
const handlePageParamsEvent = (
	params: unknown[],
	pathname: string
): boolean => {
	if (!params?.length) return false

	const currentPageParams = params[0] as PageParams
	if (typeof currentPageParams !== "object" || currentPageParams === null) {
		console.warn("Invalid page params:", currentPageParams)
		return false
	}

	const keys = Object.keys(currentPageParams)
	if (keys.length === 0) return false

	const eventName = keys[0]
	const eventKey = `${pathname}.${eventName}`
	const eventValue = currentPageParams[eventName]

	if (routerEventEmitter.getListeners(eventKey).length > 0) {
		routerEventEmitter.emit(eventKey, eventValue)
		return true
	}

	return false
}

// 修改后的popstate事件处理
window.addEventListener("popstate", (event: PopStateEvent) => {
	const routerStore = useRouterStore()
	const toPathName = event.state?.current?.slice(1) || ""

	const currentPages = routerStore.currentPages
	const historyPages = routerStore.historyPages

	const backPage = currentPages.at(-2)
	const forwardPage = historyPages[0]

	let currentPage: RouterStore.PageItem | null = null

	if (toPathName === backPage?.pathName) {
		currentPage = { ...backPage }
		routerStore.delete(1)
	} else if (toPathName === forwardPage?.pathName) {
		currentPage = { ...forwardPage }
		routerStore.deleteHistory(toPathName, true)
	}

	if (currentPage && !currentPage.cache) {
		handlePageParamsEvent(currentPage.params || [], location.pathname)
	}
})

// 添加全局路由错误处理
router.onError(error => {
	console.error("路由错误:", error)
	// 可以添加错误上报逻辑
})

export default router
